package src.server;

import src.Main;
import src.config.SysConfig;

import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

/**
 * @author CsCN
 * 作为各个Server的模板
 */
public abstract class AbstractServer {
    private final int port;
    private final int timeout;

    public AbstractServer(int port, int timeout) {
        this.port = port;
        this.timeout = timeout;
    }

    public AbstractServer(int port) {
        this(port, SysConfig.SERVER_TIMEOUT);
    }

    public final void start() {
        try {
            // 创建服务端Socket
            ServerSocket serverSocket = new ServerSocket(port);
            // 设置超时
            serverSocket.setSoTimeout(timeout);
            Socket socket;
            System.out.println(port);
            // 由running控制服务器是否运行, running变为false之后timeout毫秒, 该函数结束
            while (Main.running) {
                try {
                    System.out.println("accepting");
                    socket = serverSocket.accept();
                    System.out.println("accepted");
                    startThread(socket);
                } catch (SocketTimeoutException ignored) {
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 建立连接之后的具体操作
     *
     * @param socket socket
     */
    public abstract void startThread(Socket socket);

}
